﻿using System;
using System.IO;
using System.Linq;

namespace StoCombatLogHUD.Toolkit
{
	/// <summary>
	/// Helpers for ze Game.
	/// </summary>
	public static class GameHelpers
	{
		/// <summary>
		/// Determines whether the specified file path is a valid star trek online log directory.
		/// </summary>
		/// <param name="filePath">The file path.</param>
		/// <returns>
		///   <c>true</c> if it is; otherwise, <c>false</c>.
		/// </returns>
		public static bool IsValidStarTrekOnlineLogDirectory(string filePath)
		{
			var validLogDirectoryPaths = new[]
				{
					@"Live\logs\GameClient\Combatlog.Log",
					@"Playtest\logs\GameClient\Combatlog.Log"
				};

			var logFilePath = Path.GetDirectoryName(filePath);
			if (logFilePath == null)
				return false;

			if (!validLogDirectoryPaths.Any(filePath.EndsWith))
				return false;

			return File.Exists(logFilePath + @"\..\..\GameClient.exe");
		}

		/// <summary>
		/// Clears the contents of a file.
		/// </summary>
		/// <param name="filePath">The file path.</param>
		/// <param name="maxRetryCount">The maximum retry count.</param>
		public static void ClearFileContents(string filePath, int maxRetryCount = 20)
		{
			for (var retryCount = 0; retryCount < maxRetryCount; retryCount++)
			{
				try
				{
					using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
					{
						fileStream.SetLength(0);
					}
					return;
				}
				catch (Exception)
				{
					// ReSharper disable RedundantJumpStatement
					continue;
					// ReSharper restore RedundantJumpStatement
				}
			}
		}

		/// <summary>
		/// Converts a statistical double value to a displayable string.
		/// </summary>
		/// <param name="value">The value.</param>
		/// <returns></returns>
		public static string StatisticsValueToString(double value)
		{
			if ((int) value == 0)
				return "-";

			return value > 1000
							 ? (value / 1000).ToString("0.0k")
							 : value.ToString("0.0");
		}
	}
}
